package com.example.hblog.module.controller;

import com.example.hblog.Result;
import com.example.hblog.module.pojo.Avatar;
import com.example.hblog.module.service.AvatarService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("api")
public class AvatarController {

    @Autowired
    private AvatarService avatarService;
    @Value("${photo.dir}")
    private String realPath;


    @PostMapping("/uploadAvatar")
    public Result upload(MultipartFile file, Avatar avatar1, HttpServletRequest request)throws Exception {

        try{
            Avatar avatar = avatarService.showAvatar();
            String path = avatar.getPath();
            File file1=new File(realPath,path);
            if(file1.exists())file1.delete();//删除图片
            avatarService.clearAvatar();
            //图片保存
            String fileName = file.getOriginalFilename();
            String newFileName= UUID.randomUUID().toString()+"."+ FilenameUtils.getExtension(file.getOriginalFilename());//获取文件名后缀
            file.transferTo(new File(realPath,newFileName));
            avatar1.setPath(newFileName);
            avatarService.uploadAvatar(avatar1);
//            //设置图片地址
//            imageService.addImg(newFileName);
            String fileUrl="http://120.77.71.211:9011/";
            //文件获取路径
            fileUrl = fileUrl + request.getContextPath()  + newFileName;
            return new Result(200,"上传头像成功",fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(400,"上传头像失败",null);
        }
    }

    @ResponseBody
    @GetMapping("/showAvatar")
    public Result showAvatar() {
        try{
            Avatar avatar = avatarService.showAvatar();
            String path = "http://120.77.71.211:9011/"+avatar.getPath();
            return new Result(200,null,path);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(400,null,null);
        }

    }



}
